﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Maticsoft.DAL;
using System.Reflection;
using System.IO;

namespace BuildingForm.PersonInfo
{
    public partial class PersonSalary : Form 
    {
        public PersonSalary()
        {
            InitializeComponent();
            Init();
            bind();
        }

        private void Init()
        {
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.ShowIcon = false;
            //表头加粗，居中
            foreach (DataGridViewColumn col in this.dataGridView1.Columns)
            {
                col.SortMode = DataGridViewColumnSortMode.NotSortable;
            }
            this.dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            this.dataGridView1.ColumnHeadersDefaultCellStyle.Font = new System.Drawing.Font("SimSun", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.dataGridView1.AllowUserToAddRows = false;
            //班组
            Maticsoft.DAL.Banz_Info info = new Banz_Info();
            DataTable dt = info.GetList("").Tables[0];
            List<string> strList = new List<string>();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                strList.Add(dt.Rows[i]["bzmc"].ToString().Trim());
            }
            List<string> list = new List<string>();
            list.Add("全部");
            list.AddRange(strList);
            this.cboTeam.DataSource = list;
            //年，月
            int[] months = new int[12] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
            this.cboMonth.DataSource = months;
            this.cboMonth.Text = DateTime.Now.Month.ToString();
            int year = DateTime.Now.Year;
            int[] years = new int[12] { year-11,year-10,year - 9, year - 8, year - 7, year - 6, year - 5, year - 4, year - 3, year - 2, year - 1, year };
            this.cboYear.DataSource = years;
            this.cboYear.Text = DateTime.Now.Year.ToString();
        }

        private List<Salary> bind()
        {
            Maticsoft.DAL.Kqjl_Info info = new Kqjl_Info();
            string sql = string.Empty;
            sql = " 1=1 ";
            string team = this.cboTeam.Text.ToString().Trim();
            if (team != "全部")
            {
                sql += " and a.qybmm='" + team + "'";
            }
            int year = Convert.ToInt32(this.cboYear.Text.ToString());
            int month = Convert.ToInt32(this.cboMonth.Text.ToString());
            //sql += " and DATEPART(year,kqsj)=" + year + " and DATEPART(month,kqsj)=" + month;
            sql += "order by sfzh,kqsj";
            DataTable dt = info.GetListByPersonSalary2(sql).Tables[0];
           //同一天是否再一次打开进出
            bool isT = true;
            //是否是同一天,上一条数据的日期
            string tempDay = "";
            //是否是同一个人，上一条数据的身份证号
            string tempSFZH = "";
            //一个人的上班天数
            int num = 0;
            //上一条数据对象
            Salary salary = new Salary();
            List<Salary> list = new List<Salary>();
            for (int i = 0; i < dt.Rows.Count; i++)
            {   
                DataRow dr = dt.Rows[i];
                string sfzh = dr["sfzh"].ToString();
               
                string rq = dr["rq"].ToString();
                bool isEnter = Convert.ToBoolean(dr["jczt"]);
                //同一个人
                if (sfzh == tempSFZH && tempDay == rq && !isT)
                {
                    continue;
                }
                if (string.IsNullOrEmpty(tempSFZH) || sfzh == tempSFZH)
                {
                    if (string.IsNullOrEmpty(tempSFZH))
                    {
                        tempSFZH = sfzh;
                    }
                    if (isEnter)
                    {
                        tempDay = rq; isT = true;
                    }
                    else
                    {
                        if (rq == tempDay)
                        {
                            num++; isT = false;
                            salary.cqts = num;
                            salary.gh = dr["gh"].ToString();
                            salary.gz = dr["gz"].ToString();
                            salary.sfzh = dr["sfzh"].ToString();
                            salary.xb = dr["xb"].ToString();
                            salary.xh = 0;
                            salary.xm = dr["xm"].ToString();
                        }
                        
                    }
                }
                else
                {
                    if (isEnter)
                    {
                        tempDay = rq;
                        tempSFZH = sfzh;
                        num = 0;
                        isT = true;
                        if (!string.IsNullOrEmpty(salary.sfzh))
                        {
                            Salary s = salary;
                            list.Add(s);
                            salary = new Salary();
                        }
                    }
                }
            }
            //最后一个人信息
            if (!string.IsNullOrEmpty(salary.sfzh))
            {
                Salary s = salary;
                list.Add(s);
                salary = new Salary();
            }
            for (var i = 0; i < list.Count; i++)
            {
                list[i].xh = i + 1;
            }
            this.dataGridView1.AutoGenerateColumns = false;
            this.dataGridView1.DataSource = list;
            return list;
        }

        private List<WorkTime> GetWorkTimeList()
        {
            Maticsoft.DAL.Kqjl_Info info = new Kqjl_Info();
            string sql = string.Empty;
            sql = " 1=1 ";
            string team = this.cboTeam.Text.ToString().Trim();
            if (team != "全部")
            {
                sql += " and a.qybmm='" + team + "'";
            }
            int year = Convert.ToInt32(this.cboYear.Text.ToString());
            int month = Convert.ToInt32(this.cboMonth.Text.ToString());
            //sql += " and DATEPART(year,a.kqsj)=" + year + " and DATEPART(month,a.kqsj)=" + month;
            sql += " order by a.sfzh,a.kqsj";
            DataTable dt = info.GetList22(sql).Tables[0];
            List<WorkTime> list = new List<WorkTime>();
            string sfzh_b = string.Empty;
            string dksj_b = string.Empty;
            DateTime beginTime = DateTime.MinValue;
            DateTime endTime = DateTime.MinValue;
            WorkTime arg = new WorkTime();
            int num = 1;
            decimal worktime = 0;
            //true进 false出
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow dr = dt.Rows[i];
                string sfzh_1 = dr["sfzh"].ToString();
                string dksj_1 = dr["dksj"].ToString();
                //if (sfzh_1 != "0566805022") continue;
                if (sfzh_b.Equals(sfzh_1) && dksj_b.Equals(dksj_1))
                {
                    bool isEnter = Convert.ToBoolean(dr["jczt"]);
                    //进
                    if (isEnter)
                    {
                        beginTime = Convert.ToDateTime(dr["kqsj"]);
                    }
                    else
                    {
                        if (endTime == DateTime.MinValue && beginTime != DateTime.MinValue)
                        {
                            endTime = Convert.ToDateTime(dr["kqsj"]);
                            TimeSpan ts = endTime - beginTime;
                            decimal di = ts.Hours * 3600 + ts.Minutes * 60 + ts.Seconds;
                            worktime += di;
                            //防止一个人一天的再次
                            beginTime = DateTime.MinValue;
                            endTime = DateTime.MinValue;
                        }
                    }

                }
                else
                {
                    if (i != 0)
                    {
                        //工时大于0的才记录,不能用worktime，几秒时就是0
                        decimal gs = Math.Round(worktime / 3600, 2);
                        if (gs > 0)
                        {
                            arg.gs = Math.Round(worktime / 3600, 2);
                            worktime = 0;
                            list.Add(arg);
                            //TotalHours += gs;
                            num++;
                        }
                    }
                    //防止下一天或一个人的再次
                    beginTime = DateTime.MinValue;
                    endTime = DateTime.MinValue;
                    bool isEnter = Convert.ToBoolean(dr["jczt"]);
                    //进
                    if (isEnter)
                    {
                        beginTime = Convert.ToDateTime(dr["kqsj"]);
                    }

                    sfzh_b = sfzh_1;
                    dksj_b = dksj_1;
                    WorkTime w = new WorkTime();
                    w.xh = num;
                    w.xm = dr["xm"].ToString();
                    w.gh = dr["gh"].ToString();
                    w.sfzh = dr["sfzh"].ToString();
                    w.bz = dr["bzmc"].ToString();
                    w.gz = dr["gz"].ToString();
                    w.rq = Convert.ToDateTime(dksj_b);
                    arg = w;
                }
            }
            if (!string.IsNullOrEmpty(arg.sfzh))
            {
                arg.gs = Math.Round(worktime / 3600, 2);
                list.Add(arg);
            }
            List<WorkTime> list2 = new List<WorkTime>();
            string prevSFZH = string.Empty;
            decimal totalHours = 0m;
            WorkTime obj = new WorkTime();
            foreach (var l in list)
            {
                if (string.IsNullOrEmpty(prevSFZH))
                {
                    prevSFZH = l.sfzh;
                    obj = l;
                    totalHours = l.gs;
                }
                else
                {
                    if (prevSFZH == l.sfzh)
                    {
                        totalHours += l.gs;
                    }
                    else
                    {
                        WorkTime ww = obj;
                        ww.dygs = totalHours;
                        list2.Add(ww);
                        totalHours = 0m;
                        prevSFZH = l.sfzh;
                        obj = l;
                        totalHours = l.gs;
                    }
                }
            }
            if (!string.IsNullOrEmpty(obj.sfzh))
            {
                obj.dygs = totalHours;
                list2.Add(obj);
            }
            return list2;
        }

        private void button1_Click(object sender, EventArgs e)
        {
           bind();
        }

        public static DataSet ToDataSet(IList p_List)
        {
            DataSet result = new DataSet();
            DataTable _DataTable = new DataTable();
            if (p_List.Count > 0)
            {
                PropertyInfo[] propertys = p_List[0].GetType().GetProperties();
                foreach (PropertyInfo pi in propertys)
                {
                    _DataTable.Columns.Add(pi.Name, pi.PropertyType);//columnName Type
                }

                for (int i = 0; i < p_List.Count; i++)
                {
                    ArrayList tempList = new ArrayList();    //一行数据的数组
                    foreach (PropertyInfo pi in propertys)
                    {
                        object obj = pi.GetValue(p_List[i], null);//p_List[i]是集合中的某一个对象，GetValue 返回其属性值
                        tempList.Add(obj);
                    }
                    object[] array = tempList.ToArray();
                    _DataTable.LoadDataRow(array, true); //LoadDataRow 查找和更新特定行。 如果找不到任何匹配行，则使用给定值创建新行
                }
            }
            result.Tables.Add(_DataTable);
            return result;
        }


        private void btnExport_Click(object sender, EventArgs e)
        {

            try
            {
                List<Salary> list = bind();
                List<WorkTime> list2 = GetWorkTimeList();
                foreach (var l in list)
                {
                    foreach (var ll in list2)
                    {
                        if (l.sfzh == ll.sfzh)
                        {
                            l.dykq = ll.dygs; break;
                        }
                    }
                }
                if (list.Count == 0)
                {
                    MessageBox.Show("没有数据！"); return;
                }

                SaveFileDialog saveFileDialog1 = new SaveFileDialog();
                //设置文件类型   
                saveFileDialog1.Filter = " xls files(*.xls)|*.xls";
                //设置默认文件类型显示顺序   
                saveFileDialog1.FilterIndex = 2;
                //保存对话框是否记忆上次打开的目录   
                saveFileDialog1.RestoreDirectory = true;
                saveFileDialog1.FileName = "员工工资表" + DateTime.Now.ToString("yyyyMMdd");
                //点了保存按钮进入   
                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    string team = this.cboTeam.Text.ToString().Trim();
                    string fileName = saveFileDialog1.FileName;
                    string[] oldCols = new string[] { "xh",  "xm", "xb","sfzh", "yhkh","rgz","cqts","dykq","yfgz","kk","sfgz","lkrqm"};
                    string[] newCols = new string[] { "序号", "姓名", "性别","身份证号","银行卡号","日工资","出勤天数","当月考勤","应发工资","扣款","实发工资","领款人签字"};
                    DataTable dt = ToDataSet(list).Tables[0];
                    ExcelHelper.ExportByPersonSalary(dt, "员工工资表", fileName, "Sheet1", oldCols, newCols,team);
                    MessageBox.Show("导出文件成功！"); return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("导出文件故障！"); return;
            }
        }

        private void PersonSalary_Load(object sender, EventArgs e)
        {

        }

        private void label3_Click(object sender, EventArgs e)
        {

        }

        private void cboYear_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

    }
    public class Salary
    {
        public int xh { get; set; }
        public string gh { get; set; }
        public string xm { get; set; }
        public string xb { get; set; }
        public string gz { get; set; }
        public string sfzh { get; set; }
        public int cqts { get; set; }
        public string yhkh{get;set;}
        public string rgz{get;set;}
        public string yfgz{get;set;}
        public string kk{get;set;}
        public string sfgz{get;set;}
        public string lkrqm{get;set;}
        public decimal dykq { get; set; }
    }
}
